/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       nxustreaming.cpp
 * Author:     twoja stara
 * Created on: 2009-11-02
 *
 **********************************************************************************************************************/

#include "nxustreaming.h"

namespace mGameEngine
{
namespace Physics
{

NxuMemoryWriteBuffer::NxuMemoryWriteBuffer() :
    currentSize(0), maxSize(0), data(NULL)
{
}

NxuMemoryWriteBuffer::~NxuMemoryWriteBuffer()
{
    NX_DELETE_ARRAY( data);
}

void NxuMemoryWriteBuffer::clear()
{
    currentSize = 0;
}

NxStream &NxuMemoryWriteBuffer::storeByte(NxU8 b)
{
    storeBuffer(&b, sizeof(NxU8));
    return *this;
}
NxStream &NxuMemoryWriteBuffer::storeWord(NxU16 w)
{
    storeBuffer(&w, sizeof(NxU16));
    return *this;
}
NxStream &NxuMemoryWriteBuffer::storeDword(NxU32 d)
{
    storeBuffer(&d, sizeof(NxU32));
    return *this;
}
NxStream &NxuMemoryWriteBuffer::storeFloat(NxReal f)
{
    storeBuffer(&f, sizeof(NxReal));
    return *this;
}
NxStream &NxuMemoryWriteBuffer::storeDouble(NxF64 f)
{
    storeBuffer(&f, sizeof(NxF64));
    return *this;
}
NxStream &NxuMemoryWriteBuffer::storeBuffer(const void *buffer, NxU32 size)
{
    NxU32 expectedSize = currentSize + size;
    if (expectedSize > maxSize)
    {
        maxSize = expectedSize + 4096;

        NxU8 *newData = new NxU8[maxSize];
        NX_ASSERT(newData != NULL);

        if (data)
        {
            memcpy(newData, data, currentSize);
            delete[] data;
        }
        data = newData;
    }
    memcpy(data + currentSize, buffer, size);
    currentSize += size;
    return *this;
}

NxuMemoryReadBuffer::NxuMemoryReadBuffer(const NxU8 *data) :
    buffer(data)
{
}

NxuMemoryReadBuffer::~NxuMemoryReadBuffer()
{
    // We    don't    own    the    data =>    no delete
}

NxU8 NxuMemoryReadBuffer::readByte() const
{
    NxU8 b;
    memcpy(&b, buffer, sizeof(NxU8));
    buffer += sizeof(NxU8);
    return b;
}

NxU16 NxuMemoryReadBuffer::readWord() const
{
    NxU16 w;
    memcpy(&w, buffer, sizeof(NxU16));
    buffer += sizeof(NxU16);
    return w;
}

NxU32 NxuMemoryReadBuffer::readDword() const
{
    NxU32 d;
    memcpy(&d, buffer, sizeof(NxU32));
    buffer += sizeof(NxU32);
    return d;
}

float NxuMemoryReadBuffer::readFloat() const
{
    float f;
    memcpy(&f, buffer, sizeof(float));
    buffer += sizeof(float);
    return f;
}

double NxuMemoryReadBuffer::readDouble() const
{
    double f;
    memcpy(&f, buffer, sizeof(double));
    buffer += sizeof(double);
    return f;
}

void NxuMemoryReadBuffer::readBuffer(void *dest, NxU32 size) const
{
    memcpy(dest, buffer, size);
    buffer += size;
}

}
}

